package com.magic.himalaya.fragments;

import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.magic.himalaya.R;
import com.magic.himalaya.adapters.RecommendListAdapter;
import com.magic.himalaya.base.BaseApplication;
import com.magic.himalaya.base.BaseFragment;
import com.magic.himalaya.interfaces.IRecommendViewCallBack;
import com.magic.himalaya.presenters.AlbumDetailPresenter;
import com.magic.himalaya.presenters.RecommendPresenter;
import com.magic.himalaya.utils.Constants;
import com.magic.himalaya.utils.DisplayUtils;
import com.magic.himalaya.DetailActivity;
import com.magic.himalaya.views.LoaderView;
import com.ximalaya.ting.android.opensdk.model.album.Album;

import java.util.List;

/**
 * @description: PackageName->com.magic.himalaya.fragments
 * @create: 2022/1/20-21:06
 */
public class RecommendFragment extends BaseFragment implements IRecommendViewCallBack {

    private static final String TAG = RecommendFragment.class.getSimpleName();

    private View rootView;//Fragment_recommend根布局

    private RecyclerView recyclerView;//RecyclerView组件

    private RecommendListAdapter recommendListAdapter;//RecyclerView适配器

    private RecommendPresenter mRecommendPresenter;//Recommend接口实现的逻辑对象
    private LoaderView loaderView;
    private TwinklingRefreshLayout mRefreshLayout;


    /**
     * 渲染主页面内容
     *
     * @param inflater
     * @param container
     * @return
     */
    @Override
    protected View onSubViewLoaded(LayoutInflater inflater, ViewGroup container) {


        loaderView = new LoaderView(getContext()) {
            @Override
            public View getSuccessView(ViewGroup container) {
                return createSuccessView(inflater, container);
            }
        };

        mRecommendPresenter = RecommendPresenter.getInstance();//获取逻辑层对象
        mRecommendPresenter.registerViewCallBack(this);//实现它的回调，用此类来实现
        mRecommendPresenter.getRecommendList();//开始拿取数据,请求网络

        //与父类解绑
        if (loaderView.getParent() instanceof ViewGroup) {
            ((ViewGroup) loaderView.getParent()).removeView(loaderView);
        }

        //设置重新请求网络函数
        loaderView.setRecommendData(() -> requestRecommendData());

        return loaderView;
    }

    /**
     * 网络不佳的时候
     * 点击图标进行重新请求数据
     */
    private void requestRecommendData() {
        if (mRecommendPresenter != null)
            mRecommendPresenter.getRecommendList();
    }

    /**
     * 成功获取到数据时将数据渲染到页面中
     *
     * @param inflater
     * @param container
     * @return
     */
    private View createSuccessView(LayoutInflater inflater, ViewGroup container) {
        rootView = inflater.inflate(R.layout.fragment_recommend, container, false);//获取布局文件
        recyclerView = rootView.findViewById(R.id.rv_view);//获取组件

        recyclerView.setHasFixedSize(true); //设置保持固定大小，这样可优化RecyclerView的性能
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext()); //创建布局管理器
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);   //设置滚动方向
        recyclerView.setLayoutManager(linearLayoutManager); //需要给recyclerView设置linearLayoutManager

        //增加一点装饰线，用于分割每条Item数据
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view,
                                       @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                DisplayUtils displayUtils = DisplayUtils.getInstance(view.getContext());
                outRect.top = displayUtils.dipToPx(5);
                outRect.bottom = displayUtils.dipToPx(5);
                outRect.left = displayUtils.dipToPx(5);
                outRect.right = displayUtils.dipToPx(5);
            }

            @Override
            public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }
        });

        recommendListAdapter = new RecommendListAdapter();//创建Recycler适配器

        //点击ITEM后的跳转操作
        recommendListAdapter.setOnCallBack((album, position) -> {
            AlbumDetailPresenter.getInstance().setmTargetAlbum(album); //将Album实体存进AlbumDetail实现类中
            Intent intent = new Intent(getContext(), DetailActivity.class);
            startActivityForResult(intent, Constants.REQUEST_CODE); //进行跳转至下一个详情Activity
        });

        recyclerView.setAdapter(recommendListAdapter);//增加适配器

        initRefreshLayout();

        return rootView;
    }

    /**
     * 初始化下拉刷新上拉加载更多框架组件
     */
    private void initRefreshLayout() {
        //获得上下刷新框架组件
        mRefreshLayout = rootView.findViewById(R.id.refreshLayout);
        mRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            //上拉刷新
            @Override
            public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                mRecommendPresenter.getRecommendList();//开始拿取数据,请求网络
                mRefreshLayout.finishRefreshing();
                mRefreshLayout.finishLoadmore();

            }

            //下拉加载更多
            @Override
            public void onLoadMore(final TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);

                mRecommendPresenter.loadMore();//开始拿取数据,请求网络
                mRecommendPresenter.setOnDataListener((str) -> {
                    if (str != null) {
                        Toast.makeText(BaseApplication.getsAppContext(),str,Toast.LENGTH_SHORT).show();
                    }
                    mRefreshLayout.finishLoadmore();
                });//获得了数据后关闭加载UI
            }
        });
    }


    /**
     * 实现IRecommendViewCallBack回调 成功获取到数据时
     *
     * @param result
     */
    @Override
    public void getRecommendListLoaded(List<Album> result) {
        loaderView.updateStatus(LoaderView.UIStatus.SUCCESS); //更新页面状态，此时会调用createSuccessView方法进行渲染,当前为无数据状态
        recommendListAdapter.setData(result);//设置数据,重新进行渲染
    }

    /**
     * 实现IRecommendViewCallBack回调 网络出错时
     */
    @Override
    public void onNetworkError() {
        loaderView.updateStatus(LoaderView.UIStatus.NETWORK_ERROR); //更新页面状态
    }

    /**
     * 实现IRecommendViewCallBack回调 数据为空时
     */
    @Override
    public void onRecommendEmpty() {
        loaderView.updateStatus(LoaderView.UIStatus.EMPTY); //更新页面状态
    }

    /**
     * 实现IRecommendViewCallBack回调 加载中时...
     */
    @Override
    public void onLoading() {
        loaderView.updateStatus(LoaderView.UIStatus.LOADING); //更新页面状态
    }

    /**
     * 为防止内存泄漏，在视图不在显示的时候将UI渲染清除
     */
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mRecommendPresenter != null) {
            mRecommendPresenter.unRegisterViewCallBack(this);
        }
    }

}
